const timeExtend = require('./app/extend/time')

let accessToken = require('./app/global').accessToken

module.exports = app => {
  app.beforeStart(function* () {
    let getAccessToken = () => {
      let corpId = app.config.wxCorp.corpId
      let secret = app.config.wxCorp.secret

      if ((!corpId || !corpId.length) || (!secret || !secret.length)) {
        console.log(corpId, secret, 'no corpId/secret')
        return app.logger.error(`[egg-wx-corp] getAccessToken`, 'no corpId/secret')
      }

      return app.curl(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${secret}`, {
        timeout: 20000,
        dataType: 'json'
      }).then((result) => {
        result = result.data

        accessToken.token = result.access_token
        accessToken.expiresIn = result.expires_in
        accessToken.expiresAt = timeExtend.getExpire(accessToken.expiresIn * 1000)
        app.logger.debug(`[egg-wx-corp] getAccessToken`, accessToken)

        setTimeout(() => {
          getAccessToken()
        }, (accessToken.expiresIn - 100) * 1000)
      })
    }

    getAccessToken().then(() => {
      app.messenger.sendToApp('wx_corp_ready', {})
    })
    app.logger.warn('[egg-wx-corp] plugins start')
  })
}
